<template>
  <div class="center-page">
    <div class="header">
      <h1>齐大图书商城 · 个人中心</h1>
      <div class="header-actions">
        <el-button @click="goBooks">返回图书列表</el-button>
        <el-button type="primary" @click="goBooks">去图书页面</el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :xs="24" :md="10">
        <el-card shadow="hover" class="card">
          <template #header>
            <div class="card-header">
              <span>用户信息</span>
              <el-button type="primary" size="small" @click="onSaveUser" :loading="savingUser">保存</el-button>
            </div>
          </template>

          <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="90px">
            <el-form-item label="用户ID">
              <el-input v-model="userForm.id" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="14">
        <el-card shadow="hover" class="card">
          <template #header>
            <div class="card-header">
              <span>收货地址</span>
              <div>
                <el-button size="small" @click="resetAddress">重置</el-button>
                <el-button type="primary" size="small" @click="addNewAddress" :loading="addingAddress">添加</el-button>
              </div>
            </div>
          </template>

          <el-form :model="addressForm" ref="addressFormRef" label-width="90px">
            <el-form-item label="联系人">
              <el-input v-model="addressForm.name" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="addressForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="addressForm.detail" type="textarea" placeholder="请输入详细地址" />
            </el-form-item>
          </el-form>

          <el-divider />

          <el-table :data="addressList" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="联系人" />
            <el-table-column prop="phone" label="电话" />
            <el-table-column prop="detail" label="地址" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getUserInfo, modifyUserInfo, addAddress, getAddressList } from '@/api/user'

const router = useRouter()

// 简单从本地存储获取用户ID（真实项目可从登录态或store中获取）
const userId = ref<number>(1)

// 用户信息
const userFormRef = ref<FormInstance>()
const savingUser = ref(false)
const userForm = reactive<any>({ id: '', username: '', email: '' })

const userRules: FormRules = {
  username: [ { required: true, message: '请输入用户名', trigger: 'blur' } ],
  email: [ { required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '邮箱格式不正确', trigger: 'blur' } ]
}

const loadUser = async () => {
  try {
    const res = await getUserInfo(userId.value)
    const data = res.data?.user_info || res.data || {}
    userForm.id = data.id ?? userId.value
    userForm.username = data.username ?? ''
    userForm.email = data.email ?? ''
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '获取用户信息失败')
  }
}

const onSaveUser = async () => {
  if (!userFormRef.value) return
  try {
    await userFormRef.value.validate()
    savingUser.value = true
    await modifyUserInfo(userId.value, { username: userForm.username, email: userForm.email })
    ElMessage.success('保存成功')
    await loadUser()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '保存失败')
  } finally {
    savingUser.value = false
  }
}

// 地址管理
const addressFormRef = ref<FormInstance>()
const addingAddress = ref(false)
const addressForm = reactive<any>({ name: '', phone: '', detail: '' })
const addressList = ref<any[]>([])

const resetAddress = () => {
  addressForm.name = ''
  addressForm.phone = ''
  addressForm.detail = ''
}

const addNewAddress = async () => {
  try {
    addingAddress.value = true
    await addAddress({ user_id: userId.value, ...addressForm })
    ElMessage.success('已添加')
    resetAddress()
    await loadAddresses()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '添加失败')
  } finally {
    addingAddress.value = false
  }
}

const loadAddresses = async () => {
  try {
    const res = await getAddressList(userId.value)
    const data = res.data
    const list = Array.isArray(data?.address_list)
      ? data.address_list
      : Array.isArray(data)
        ? data
        : []
    addressList.value = list
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '获取地址列表失败')
  }
}

onMounted(async () => {
  await loadUser()
  await loadAddresses()
})

const goBooks = () => {
  router.push('/books')
}
</script>


<style scoped>
.center-page { padding: 20px; }
.header { margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between; }
.header-actions { display: flex; gap: 8px; }
.card { margin-bottom: 20px; }
.card-header { display: flex; align-items: center; justify-content: space-between; }
</style>
